<template>
	<div class="container">
		<div style="width: 100%;display: flex;flex-direction: row;align-items: center;">
			<el-button type="primary" icon="el-icon-plus" @click="editVisible = true" :disabled="userAuthority == 1"
				class="toolBarButton">
				新增
			</el-button>
			<div class="selectBox">
				<div>状态：</div>
				<el-select v-model="portType" filterable placeholder="请选择" clearable>
					<el-option v-for="item in typeList" :label="item.name" :value="item.value">
					</el-option>
				</el-select>
			</div>
			<div style="margin-left: 10px;margin-bottom: 20px;">
				<el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
			</div>
		</div>
		<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
			class="tableData" :data="tableDataFn" border stripe :fit="true" style="width: 100%" @row-click="rowClick">
			<el-table-column type="index" :index="1" width="50" label="序号">
			</el-table-column>

			<template v-for="item in tableColumns">
				<el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable" :width="item.width"
					align="center" v-if="item.isShow" :key="item.prop">
					<template v-slot="scope">
						<template v-if="item.format == 'Status'">
							<!-- <template v-if="portStatus(scope.row) === 'Y'">
                <el-tag type="success">正常</el-tag>
              </template>
              <template v-else-if="portStatus(scope.row) === 'N'">
                <el-tag type="danger">异常</el-tag>
              </template> -->
							<template>
								<el-tag style="cursor: pointer;" type="info">查看端口状态</el-tag>
							</template>
						</template>
						<template v-else-if="item.format == 'handleRow'">
							<div>
								<el-button type="warning" @click="editNode(scope.row)" :disabled="userAuthority == 1">编辑
								</el-button>
								<template v-if="scope.row['isenabled'] == 'Y'">
									<el-button type="danger" @click="editNodeMonitor(scope.row, 'N')"
										v-show="userAuthority != 1" :loading="scope.row.editNodeMonitorBtnDisabled">
										关闭监控
									</el-button>
								</template>
								<template v-else>
									<el-button type="success" @click="editNodeMonitor(scope.row, 'Y')"
										v-show="userAuthority != 1" :loading="scope.row.editNodeMonitorBtnDisabled">
										开启监控
									</el-button>
								</template>
							</div>
						</template>
						<template v-else-if="item.format == 'type'">
							<template v-if="scope.row['status'] === 'Y'">
								<el-tag type="success">正常</el-tag>
							</template>
							<template v-else-if="scope.row['status'] == 'N' || scope.row['status'] == ''">
								<el-tag type="danger">异常</el-tag>
							</template>
							<template v-else>
								<el-tag type="warning">未监控</el-tag>
							</template>
						</template>
						<template v-else>
							<div>
								{{ scope.row[item.prop] }}
							</div>
						</template>
					</template>


				</el-table-column>
			</template>
		</el-table>
		<v-pagination :dataTotal="postData.dataTotal" :curPage="postData.curPage" :pageSize="postData.pageSize"
			@getCurPage="getPaginationCurPage" @getPageSize="getPaginationPageSize">
		</v-pagination>

		<!-- 新建、编辑对话框 -->
		<el-dialog :visible.sync="editVisible" width="24%" @close="resetForm('nodeForm')">
			<el-form :model="nodeForm" :rules="nodeFormRules" ref="nodeForm" label-width="120px">
				<el-form-item label="IP" prop="ip">
					<el-input v-model="nodeForm.ip"></el-input>
				</el-form-item>
				<el-form-item label="标签" prop="lable">
					<el-input v-model="nodeForm.lable"></el-input>
				</el-form-item>
				<el-form-item label="端口" prop="port">
					<el-input v-model="nodeForm.port" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字">
					</el-input>
				</el-form-item>
				<el-form-item label="监控状态" prop="isenabled">
					<el-radio-group v-model="nodeForm.isenabled"
						:fill="nodeForm.isenabled == 'Y' ? '#67C23A' : '#F56C6C'">
						<el-radio-button key="Y" label="Y">开启</el-radio-button>
						<el-radio-button key="N" label="N">关闭</el-radio-button>
					</el-radio-group>
				</el-form-item>
			</el-form>

			<span slot="footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitData('nodeForm')" :disabled="submitBtnDisabled">
					确 定
				</el-button>
			</span>
		</el-dialog>
		<!-- 端口信息 -->
		<el-drawer title="端口状态" :visible.sync="drawer" direction="rtl" size="50%" :destroy-on-close="true"
			@close="drawerClose" :show-close="false">
			<div class="drawerTab">
				<div>
					<p>开始日期:</p>
					<el-date-picker class="blockStart" v-model="drawerPostData.time" type="datetime" placeholder="开始日期"
						:clearable="false" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss">
					</el-date-picker>
				</div>
				<div>
					<p>结束日期:</p>
					<el-date-picker class="blockEnd" v-model="drawerPostData.time2" type="datetime" placeholder="结束日期"
						:clearable="false" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss">
					</el-date-picker>
				</div>
				<div>
					<el-button type="primary" @click="getPortData">查询</el-button>
				</div>
			</div>
			<el-table :data="getDrawerStoreTableData()" v-loading="drawerTableLoading" element-loading-text="拼命加载中"
				element-loading-spinner="el-icon-loading" :fit="true">
				<el-table-column align="center" prop="IP" label="IP"></el-table-column>
				<el-table-column align="center" prop="PORT" label="端口"></el-table-column>
				<el-table-column align="center" prop="STATUS" label="状态">
					<template v-slot="scope">
						<template v-if="scope.row['STATUS'] === 'Y'">
							<el-tag type="success">正常</el-tag>
						</template>
						<template v-else-if="scope.row['STATUS'] === 'N'">
							<el-tag type="danger">异常</el-tag>
						</template>
						<template v-else>
							<el-tag type="warning">未监控</el-tag>
						</template>
					</template>
				</el-table-column>
				<el-table-column align="center" prop="CREAREDATE" label="时间"></el-table-column>
			</el-table>
			<v-pagination :dataTotal="getDrawerDataTotal()" :curPage="getDrawerCurPage()"
				:pageSize="getDrawerPageSize()" @getCurPage="SetDrawerPaginationCurPage"
				@getPageSize="setDrawerPaginationPageSize">
			</v-pagination>
		</el-drawer>
	</div>
</template>

<script>
	import {
		getJavaServerNotData,
		getJavaServerData
	} from "@/api/index.js";
	import vPagination from "common/Pagination.vue";
	import tableColumns from "./PortIndexColumns.js";
	import {
		getUserData
	} from "@/utils/IndexedDB.js";
	import {
		mapGetters,
		mapMutations,
		mapActions,
		mapState
	} from "vuex";
	import moment from "moment";
	export default {
		components: {
			vPagination,
		},

		data() {
			return {
				postData: {
					curPage: 1,
					pageSize: 20,
					dataTotal: 0,
				},
				portType: '',
				typeList: [{
					name: '正常',
					value: 'Y'
				}, {
					name: '异常',
					value: 'N'
				}],
				tableData: [],
				dataTotal: 0,
				tableColumns: tableColumns,
				editVisible: false,
				submitBtnDisabled: false,
				editNodeMonitorBtnDisabled: false,
				nodeForm: {
					// tid: '',    编辑用到
					ip: "",
					port: 1521,
					isenabled: "N",
					lable: ''
				},
				nodeFormRules: {
					ip: [{
							required: true,
							message: "请输入IP",
							trigger: "blur"
						},
						{
							pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
							message: "请输入正确的IP",
						},
					],
					port: [{
						required: true,
						message: "请输入端口",
						trigger: "blur"
					}],
				},
				loading: true,
				userAuthority: "",
				portStatusData: [],
				drawer: false,
				// drawerTableData: [],
				drawerTableLoading: false,
				drawerPostData: {
					time: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
					time2: moment().format("YYYY-MM-DD HH:mm:ss"),
					tid: "",
				},
				pickerOptions: {
					disabledDate: (time) => {
						return time.getTime() > Date.now();
					},
				},
			};
		},
		created() {
			this.getTableData();
		},
		computed: {
			tableDataFn() {
				return this.tableData.filter((item) => {
					return item;
				});
			},
		},
		methods: {
			...mapMutations({
				getPagination: "ManagementPort/pagination",
				setTableData: "ManagementPort/setItem",
			}),
			...mapGetters({
				getStoreTableData: "ManagementPort/getItem",
				getDrawerStoreTableData: "ManagementPortStatus/getTableData",
				getDrawerCurPage: "ManagementPortStatus/getCurPage",
				getDrawerPageSize: "ManagementPortStatus/getpageSize",
				getDrawerDataTotal: "ManagementPortStatus/getDataTotal",
			}),
			...mapActions({
				SetDrawerPaginationCurPage: "ManagementPortStatus/getPaginationCurPage",
				setDrawerPaginationPageSize: "ManagementPortStatus/getPaginationPageSize",
				setDrawerTableData: "ManagementPortStatus/setTableData"
			}),
			async getTableData() {
				await getUserData("userBase", "infoBase", 0).then((res) => {
					this.userAuthority = res.userAuthority;
				});
				this.loading = true;
				getJavaServerNotData("/Sp/showportinfo")
					.then((res) => {

						if (Array.isArray(res)) {
							res.forEach((item) => {
								item.editNodeMonitorBtnDisabled = false;
							});
							this.postData.dataTotal = res.length;
							this.setTableData(res);
							this.getTableDataForVuex();
							this.$message({
								message: "请求成功",
								type: "success",
								duration: 500,
							});
						} else {
							this.$message({
								message: "请求失败",
								type: "error",
								duration: 500,
							});
							this.tableData = [];
						}
					})
					.finally(() => {
						this.loading = false;
					});
			},
			getPortData() {
				this.drawerTableLoading = true;
				getJavaServerData("/Sp/showoneport", {
						...this.drawerPostData
					})
					.then((_) => {

						if (Array.isArray(_)) {
							let data = _.map((item) => {
								return {
									// TID: _.tid,
									IP: item.ip,
									PORT: item.port,
									STATUS: item.status,
									CREAREDATE: item.recordTime,
								};
							});
							this.setDrawerTableData(data)

							this.$message({
								type: "success",
								message: "请求成功",
								duration: 500,
							});
						} else {
							this.$message({
								type: "error",
								message: "请求失败",
								duration: 3000,
							});
							this.setDrawerTableData([])
						}
					})
					.finally(() => {
						this.drawerTableLoading = false;
					});
			},
			getTableDataForVuex() {
				this.getPagination(this.postData);
				this.tableData = this.getStoreTableData();
			},
			getPaginationCurPage(val) {
				this.postData.curPage = val;

				this.getTableDataForVuex();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				this.getTableDataForVuex();
			},
			resetForm(formName) {
				let _data = new Object();
				Object.assign(_data, this.$options.data()[formName]);
				this.$data[formName] = _data;

				// 移除表单校验结果
				this.$refs[formName] && this.$refs[formName].clearValidate();
			},
			search() {
				getJavaServerNotData("/Sp/showportinfo")
					.then((res) => {
						this.tableData = res
						if (this.portType == 'Y') {
							this.tableData = this.tableData.filter(item => item.status == 'Y');
						} else if (this.portType == 'N') {
							this.tableData = this.tableData.filter(item => item.status !== 'Y');
						}
					})
			},
			submitData(formName) {
				let _this = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.nodeForm = this.nodeForm;
						// 禁用按钮，避免重复提交
						this.submitBtnDisabled = true;
						let _url = this.nodeForm.hasOwnProperty("tid") ?
							"/Sp/updateportinfo" :
							"/Sp/addport";
						getJavaServerData(_url, this.nodeForm)
							.then((_) => {
								if (_ === "success") {
									this.$message({
										message: "操作成功",
										type: "success",
										duration: 500,
									});
									this.editVisible = false;
									this.getTableData();
								} else {
									this.$message({
										message: "操作失败,原因:" + _,
										type: "error",
										duration: 3000,
									});
								}
							})
							.finally(() => {
								this.submitBtnDisabled = false;
							});
					} else {
						return false;
					}
				});
			},
			editNode(rowData) {
				for (const key in this.nodeForm) {
					if (rowData.hasOwnProperty(key)) {
						this.nodeForm[key] = rowData[key];
					}
				}
				this.nodeForm.tid = rowData.tid;
				this.editVisible = true;
			},
			editNodeMonitor(rowData, flag) {
				// 禁用按钮
				const ThisRowData = rowData;
				ThisRowData.editNodeMonitorBtnDisabled = true;

				// 数据处理
				let _postData = {
					...this.nodeForm
				};
				for (const key in _postData) {
					if (rowData.hasOwnProperty(key)) {
						_postData[key] = rowData[key];
					}
				}
				_postData.tid = rowData.tid;
				_postData.isenabled = flag;
				getJavaServerData("/Sp/updateportinfo", _postData)
					.then((_) => {
						if (_ === "success") {
							this.$message.success("操作成功");
						} else {
							this.$message.error("操作失败");
						}
					})
					.finally(() => {
						setTimeout(() => {
							ThisRowData.editNodeMonitorBtnDisabled = false;
							this.getTableData();
						}, 500);
					});
			},
			rowClick({
				tid
			}, column) {
				if (column.label !== "操作") {
					this.drawer = true;
					this.drawerPostData.tid = tid;
					this.getPortData();
				}
			},
			drawerClose() {
				this.drawerPostData = {
					time: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
					time2: moment().format("YYYY-MM-DD HH:mm:ss"),
					tid: "",
				};
			},
		},
		watch: {
			// 'drawerPostData.time':function(n){
			//   this.drawerPostData.time=moment(n).format("YYYY-MM-DD HH:mm:ss");
			// },
			// 'drawerPostData.time2':function(n){
			//  this.drawerPostData.time2 = moment(n).format("YYYY-MM-DD HH:mm:ss");
			// }
		},
	};
</script>

<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.selectBox {
		width: 300px;
		height: 50px;
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-left: 10px;
		margin-bottom: 20px;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.toolBarButton {
		float: left;
		margin-bottom: 20px;
		margin-right: 20px;
	}

	.drawerTab {
		margin-left: 15px;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.drawerTab div,
	.drawerTab div p,
	.drawerTab div button {
		margin: 5px;
	}

	.drawerTab div p {
		display: inline;
		font-size: 15px;
	}
</style>
